import cv2
import numpy as np

# 全局变量
brush_color = (0, 0, 0)  # 初始画笔颜色为黑色
brush_radius = 5  # 初始画笔半径
max_count = 50 # 轨迹栏的最大值

# 回调函数
def nothing(x):
    pass

# 鼠标回调函数
def draw_circle(event, x, y, flags, param):
    global brush_color, brush_radius
    if event == cv2.EVENT_LBUTTONDOWN:  # 鼠标左键按下
        cv2.circle(img, (x, y), brush_radius, brush_color, -1)  # 绘制实心圆
    elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):  # 鼠标移动并按下左键
        cv2.circle(img, (x, y), brush_radius, brush_color, -1)  # 绘制实心圆

# 创建一个黑色图像
img = np.zeros((600, 800, 3), np.uint8)

# 创建窗口
window_name = 'Paint Program'
cv2.namedWindow(window_name)

# 创建轨迹栏来调整画笔颜色 (RGB)
cv2.createTrackbar('R', window_name, 0, 255, nothing)
cv2.createTrackbar('G', window_name, 0, 255, nothing)
cv2.createTrackbar('B', window_name, 0, 255, nothing)

# 创建轨迹栏来调整画笔半径
cv2.createTrackbar('Brush Size', window_name, brush_radius, max_count, nothing)

# 设置鼠标回调
cv2.setMouseCallback(window_name, draw_circle)

while True:
    # 获取轨迹栏的当前值
    r = cv2.getTrackbarPos('R', window_name)
    g = cv2.getTrackbarPos('G', window_name)
    b = cv2.getTrackbarPos('B', window_name)
    brush_radius = cv2.getTrackbarPos('Brush Size', window_name)

    # 根据轨迹栏的值更新画笔颜色
    brush_color = (b, g, r)

    # 显示当前图像
    cv2.imshow(window_name, img)

    # 检测按键，按 ESC 键退出
    k = cv2.waitKey(1) & 0xFF
    if k == 27:  # ESC 键退出
        break

# 释放资源并关闭窗口
cv2.destroyAllWindows()
